package com.nakamachizu.controller.mixi;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;
import org.w3c.dom.Document;

import com.nakamachizu.service.XmlGenService;

public class GadgetController extends Controller {

    @Override
    public Navigation run() throws Exception {
        
        XmlGenService xgs = new XmlGenService();
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setValidating(false);
        DocumentBuilder builder = factory.newDocumentBuilder();

        
        Document xml = null;
        
        Velocity.init("WEB-INF/velocity_conf.properties");
        VelocityContext context = new VelocityContext();

        
        String xmlStr = null;
        StringWriter sw = new StringWriter();
        Template template = Velocity.getTemplate("mixi/pc/gadget.xml", "UTF-8");
        template.merge(context, sw);
        xmlStr = sw.toString();
        sw.flush();
        
        InputStream is = new ByteArrayInputStream(xmlStr.getBytes("UTF-8"));
        try{
            xml = builder.parse(is);
        }finally{
            is.close();
        }
        
        xgs.printXml(response.getOutputStream(), xml);
        
        return null;
    }
}
